<script setup lang="ts">
import { useCartStore } from '@/stores/cart'
import { useRouter } from 'vue-router'

const cart = useCartStore()
const router = useRouter()

function goCheckout(){
  if(cart.items.length === 0) return
  router.push({ name: 'checkout' })
}
</script>

<template>
  <div class="container">
    <h2>购物车</h2>
    <table class="cart">
      <thead>
        <tr>
          <th>商品</th>
          <th>单价</th>
          <th>数量</th>
          <th>小计</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="it in cart.items" :key="it.skuId">
          <td class="prod">
            <img :src="it.picUrl" alt="" />
            <div class="name">{{ it.name }}</div>
          </td>
          <td>￥{{ it.price.toFixed(2) }}</td>
          <td>
            <input type="number" min="1" :value="it.quantity" @change="cart.updateQuantity(it.skuId, Number(($event.target as HTMLInputElement).value))" />
          </td>
          <td>￥{{ (it.price * it.quantity).toFixed(2) }}</td>
          <td><button @click="cart.remove(it.skuId)">删除</button></td>
        </tr>
      </tbody>
    </table>

    <div class="summary">
      合计：<b>￥{{ cart.totalPrice.toFixed(2) }}</b>
      <button :disabled="cart.items.length===0" @click="goCheckout">去结算</button>
    </div>
  </div>
</template>

<style scoped>
.cart { width: 100%; border-collapse: collapse; }
.cart th, .cart td { border-bottom: 1px solid #eee; padding: 12px; text-align: left; }
.prod { display: flex; align-items: center; gap: 8px; }
.prod img { width: 60px; height: 60px; object-fit: cover; border: 1px solid #eee; }
.summary { display: flex; align-items: center; gap: 12px; justify-content: flex-end; padding: 16px; }
.summary button { padding: 8px 12px; border: 1px solid #ddd; border-radius: 4px; background: #42b883; color: #fff; }
</style>